<template>
  <div class="login-body">
    <div class="login-panel">
      <div class="login-title">用户登录</div>
      <el-form
        :label-position="labelPosition"
        label-width="100px"
        :model="loginForm"
        :rules="rules"
        ref="loginFormRef"
        style="max-width: 460px"
      >
        <el-form-item prop="account">
          <el-input v-model="loginForm.account" placeholder="请输入账号">
            <!-- 插槽插入 阿里图标 -->
            <template #prefix>
              <span class="iconfont icon-yonghu"></span>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            type="password"
            v-model="loginForm.password"
            placeholder="请输入密码"
            show-password
          >
            <template #prefix>
              <span class="iconfont icon-mima"></span>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="checkCode">
          <div class="check-code-panel">
            <el-input
              class="input-panel"
              v-model="loginForm.checkCode"
              placeholder="请输入验证码"
            />
            <img
              :src="checkCodeUrl"
              class="check-code"
              @click="changeCheckCode"
            />
          </div>
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="loginForm.rememberMe" :label="true"
            >记住我</el-checkbox
          >
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="login">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref, getCurrentInstance, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import md5 from 'js-md5'
import VueCookies from 'vue-cookies'
import { ElMessage } from 'element-plus'

// 表单相关
const loginForm = reactive({
  account: '',
  password: '',
  rememberMe: true
})

const rules = reactive({
  account: [{ required: true, min: 5, max: 11, message: '账号应该5-11位', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  checkCode: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
})
const labelPosition = ref('top')

// 请求相关
const api = {
  checkCode: "api/checkCode",
  login: '/login'
}
const checkCodeUrl = ref(api.checkCode)

// 点击验证码刷新图片
const changeCheckCode = () => {
  checkCodeUrl.value = api.checkCode + "?" + new Date().getTime()
}
// 登录  密码使用md5加密   cnpm i --save js-md5
const { proxy } = getCurrentInstance() //获取组件实例
const router = useRouter() //获取全局router
const loginFormRef = ref(null)

onMounted(() => {
  const loginInfo = VueCookies.get('loginInfo')
  if (!loginInfo) {
    return
  }
  // 如果cookies存在，直接把数据填入表单
  Object.assign(loginForm, loginInfo)
})

const login = () => {
  loginFormRef.value.validate(async (valid) => {
    if (!valid) {
      return
    } else {
      const cookieLoginInfo = VueCookies.get("loginInfo")
      let cookiePassword = cookieLoginInfo == null ? null : cookieLoginInfo.password
      if (loginForm.password !== cookiePassword) {
        loginForm.password = md5(loginForm.password)
      }
      let params = {
        account: loginForm.account,
        password: loginForm.password,
        checkCode: loginForm.checkCode
      }

      let result = await proxy.Request({
        url: api.login,
        params: params,
        errorCallback: () => {
          changeCheckCode()
        }
      })
      if (!result) {
        return
      }
      proxy.Message.success("登录成功")

      setTimeout(() => {
        router.push('/')
      }, 1500)
      const loginInfo = {
        account: params.account,
        password: params.password,
        rememberMe: loginForm.rememberMe
      }
      VueCookies.set("userInfo", result.data, 0)
      if (loginForm.rememberMe === true) {
        // 如果rememberMe勾选，就把登录信息保存在cookie里面
        VueCookies.set('loginInfo', loginInfo, "7d") //保存7天
      }
    }
  })
}


</script>

<style lang="scss"  scoped>
.login-body {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: calc(100vh);
  background-image: url("../assets/bg.jpg");
  background-size: cover;
  background-position: center;
  .login-panel {
    width: 400px;
    height: 300px;
    padding: 10px 20px;
    background-color: rgba($color: #fff, $alpha: 0.7);
    box-shadow: 2px 2px 10px #ddd;
    border-radius: 8px;
    .login-title {
      height: 50px;
      margin-bottom: 12px;
      font-size: 24px;
      text-align: center;
    }
    .el-input {
      height: 40px;
    }
    .el-button {
      width: 100%;
      margin-top: -20px;
    }
    .check-code-panel {
      display: flex;
      .input-panel {
        flex: 1;
      }
      .check-code {
        position: absolute;
        right: 0;
      }
    }
  }
}
</style>